#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2014-06-17 23:04:35
# @Author  : shitao.tommy (hero007asd@gmail.com)
# @Link    : http://example.org
# @Version : $Id$

# def login_required(l_type=1):
#     '''l_type:1表示后台 2表示前端'''
#     def _login(func):
#         '''是否登陆'''
#         def _wrapper(self, *args, **kwargs):
# user_id = self.session['user']
# print user_id
# if not user_id:
# print '402sdfsdfsd'
# else:
#             ret = func(self, *args, **kwargs)
#             return ret
#         return _wrapper
#     return _login
import functools
import urlparse
import tornado
import urllib
from lib.uimethods import url
from tornado import gen
from tornado.web import asynchronous


def admin_auth(method):
    """Decorate methods with this to require that the user be logged in."""
    @asynchronous
    @gen.coroutine
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        try:
            logged = self.session['user']
        except Exception, e:
            logged = None
        # if not self.current_user:
        if logged == None:
            # jQuery 等库会附带这个头
            if self.request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                self.set_header(
                    'Content-Type', 'application/json; charset=UTF-8')
                self.write(
                    json.dumps({'success': False, 'msg': u'您的会话已过期，请重新登录！'}))
                return
            else:
                raw_url = 'http://%s/%s' % (self.request.host, 'admin/login')
                if self.request.method in ("GET", "HEAD"):
                    # url = self.get_login_url()#TODO
                    if "?" not in raw_url:
                        if urlparse.urlsplit(raw_url).scheme:
                            # if login url is absolute, make next absolute too
                            next_url = self.request.full_url()
                        else:
                            next_url = self.request.uri
                        raw_url += "?" + urllib.urlencode(dict(next=next_url))
                    self.redirect(raw_url)
                else:
                    self.redirect(raw_url)
        else:
            # ret = f(self, *args, **kwargs)
            # raise tornado.web.HTTPError(403)
            method(self, *args, **kwargs)
    return wrapper


def admin_login_required(f):
    '''后台是否登陆'''
    @asynchronous
    @gen.coroutine
    def _wrapper(self, *args, **kwargs):
        # print self.get_current_user()
        try:
            logged = self.session['user']
        except Exception, e:
            logged = None
        if logged == None:
            self.redirect('/admin/login')
        else:
            ret = f(self, *args, **kwargs)
    return _wrapper


def front_login_required(f):
    '''前端是否登陆'''
    @asynchronous
    @gen.coroutine
    def _wrapper(self, *args, **kwargs):
        logged = self.get_scookie().get('user', None)
        if logged == None:
            self.redirect('/user/login')
        else:
            return f(self, *args, **kwargs)
    return _wrapper


def is_admin_auth(auth_type):
    '''是否有权限'''
    @asynchronous
    @gen.coroutine
    def _auth(func):
        def _wrapper(self, *args, **kwargs):
            # TODO
            ret = func(self, *args, **kwargs)
            return ret
        return _wrapper
    return _auth
